package cs.upt.awp.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sun.research.ws.wadl.HTTPMethods;

import cs.upt.awp.data.Status;
import cs.upt.awp.data.TravelImage;
import cs.upt.awp.model.TravelImageViewModel;
import cs.upt.awp.model.TravelRecordViewModel;
import cs.upt.awp.services.TravelImagesServices;
import cs.upt.awp.services.TravelRecordsServices;

@Controller
@RequestMapping("/images")
public class TravelImagesController {
	
	@Autowired
	TravelImagesServices imagesServices;
	
	@Autowired
	TravelRecordsServices recordsServices;

	@RequestMapping(value = "/add", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody Status addImage(@RequestBody TravelImage image) {
		try {
			imagesServices.addEntity(image);
			return new Status(1, "Successfully added a new image!");
		} catch (Exception e) {
			return new Status(0, "Error: " + e);
		}
	}
	
	@RequestMapping(value = "/uploadFile/{recordId}", method = RequestMethod.POST)
    public 
    String uploadFileHandlerPOST(@PathVariable("recordId")long recordId, @ModelAttribute("travelImage") TravelImageViewModel travelImage,  BindingResult  request) {
		ModelAndView model = new ModelAndView();
        if (!travelImage.getFile().isEmpty()) {
            try {
                byte[] bytes = travelImage.getFile().getBytes();
 
               TravelImage img = new TravelImage();
               img.setImage(bytes);
               img.setCreationDate(new Date());
               img.setTitle(travelImage.getTitle());
               img.setDescription(travelImage.getDescription());
               img.setRecord(recordsServices.getEntityById(travelImage.getRecordId()));
               imagesServices.addEntity(img);
             
            } catch (Exception e) {
            	model.addObject("error", e.getMessage());
            }
        } else {
             	model.addObject("error","You failed to upload " + travelImage.getTitle()
                    + " because the file was empty.");
        }
        
        		return "redirect:/records/updaterecord/"+recordId;
    }
	
	@RequestMapping(value = "/uploadFile/{recordId}", method=RequestMethod.GET)
    public ModelAndView uploadFileHandlerGET(@PathVariable("recordId")long recordId) {
		ModelAndView model = new ModelAndView();
		TravelImageViewModel imgmodel = new TravelImageViewModel();
		imgmodel.setRecordId(recordId);
		model.addObject("travelImage", imgmodel);
		model.setViewName("addImage");

		return model;
     
    }
	
	@RequestMapping(value = "/imageDisplay", method = RequestMethod.GET)
	  public void showImage(@RequestParam("id") long itemId, HttpServletResponse response,HttpServletRequest request) 
	          throws Exception{


	    TravelImage img = imagesServices.getEntityById(itemId);        
	    response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
	    response.getOutputStream().write(img.getImage());


	    response.getOutputStream().close();
	}
	
	@RequestMapping(value="/{id}", method=RequestMethod.GET)
	public @ResponseBody TravelImage getTravelImage(@PathVariable("id") long id){
		TravelImage image = null;
		try {
			image = imagesServices.getEntityById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return image;
	}
	
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public @ResponseBody List<TravelImage> getAllTravelImages(){
		List<TravelImage> images = null;
		try {
			images = imagesServices.getEntityList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return images;
	}
	
	@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE)
	public @ResponseBody Status deleteTravelImage(@PathVariable("id") long id){
		try {
			imagesServices.deleteEntity(id);
			return new Status(1,"Successfully deleted image: "+id);
		} catch (Exception e) {
			return new Status(0,"Error: "+e);
		}
	}

}
